<template>
  <div>
    <el-card>
      <div slot="header">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: homePath }">设备管理</el-breadcrumb-item>
          <el-breadcrumb-item>部署设备</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="120px"
        class="el-form"
        label-position="right"
      >
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="formData.deviceId" disabled="disabled" />
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="所属项目" prop="projectId">
          <el-select
            filterable
            v-model="formData.projectId"
            placeholder="请选择"
            style="width: 100%"
            size="medium"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.projectId"
              :label="item.displayName"
              :value="item.projectId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备地址">
          <el-input v-model="formData.address" placeholder="请输入设备地址" />
        </el-form-item>
        <el-form-item label="设备描述">
          <el-input type="textarea" v-model="formData.description" :rows="2" placeholder="请输入设备描述" />
        </el-form-item>
        <el-form-item label="经纬度">
          <el-input
            v-model="formData.longitude"
            placeholder="请输入经度"
            style="width: 30%; margin-right: 20px"
          />
          <el-input v-model="formData.latitude" placeholder="请输入纬度" style="width: 30%" />
        </el-form-item>
        <el-form-item label="设备朝向">
          <el-radio-group v-model="formData.direction">
            <el-radio label="EAST">东</el-radio>
            <el-radio label="WEST">西</el-radio>
            <el-radio label="NORTH">北</el-radio>
            <el-radio label="SOUTH">南</el-radio>
            <el-radio label="NORTH_EAST">东北</el-radio>
            <el-radio label="NORTH_WEST">西北</el-radio>
            <el-radio label="SOUTH_WEST">西南</el-radio>
            <el-radio label="SOUTH_EAST">东南</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备图片">
          <div
            v-for="(item, index) in imgKeys"
            :key="item.imgkey"
            style="float: left; margin-right: 10px"
            class="img-box"
          >
            <div @click="delImg(index)" class="close-icon">
              <i class="el-icon-error"></i>
            </div>
            <img
              :src="item.httpUrl"
              class="uploadImg"
              style="border: 1px solid #ccc; width: 300px; height: 220px"
            />
          </div>
          <el-upload
            class="upload-demo"
            drag
            ref="uploadAdd"
            action
            :http-request="uploadImg"
            :on-success="uploadImgSuccess"
            :on-remove="handleRemove"
            multiple
            show-file-list
          >
            <!-- <img v-if="imgUrl" :src="imgUrl" class="uploadImg"> -->
            <!-- <div v-else> -->
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <!-- </div> -->
          </el-upload>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button
            type="primary"
            :loading="submitLoading"
            icon="el-icon-check"
            @click="submit('formRef')"
          >提 交</el-button>
          <el-button type="default" icon="el-icon-back" @click="goBack">返 回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { deploy, get } from "@/api/deviceManage";
import { listSimple } from "@/api/projectManage";
import { upload, getImg } from "@/api/common";

export default {
  name: "DeployDevice",
  data() {
    return {
      deviceId: "",
      formData: {},
      projectOptions: [],
      submitLoading: false,
      imgKeys: [],
      uploadUrls: [],
      rules: {
        deviceId: [
          { required: true, message: "请输入设备ID", trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
      },
      homePath: "/deviceManage",
      page: 1,
      search: {}
    };
  },
  created() {
    this.deviceId = this.$route.query.id;
    this.page = this.$route.query.page;
    this.search = this.$route.query.search;
    this.homePath = `${this.homePath}?page=${this.page}&search=${this.search}`;
  },
  mounted() {
    this.getMessage();
    this.getProjectList();
  },
  methods: {
    getImgFun(val) {
      //console.log(val);
      let data = {
        key: val
      };
      getImg(data).then(res => {
        for (let i = 0; i < this.imgKeys.length; i++) {
          if (this.imgKeys[i].imgkey == val) {
            this.imgKeys[i].httpUrl = res.value;
            //console.log(i);
            //console.log(this.imgKeys[i].httpUrl);
          }
        }
      });
    },
    delImg(index) {
      this.imgKeys.splice(index, 1);
    },
    uploadImg(f) {
      let param = new FormData(); //创建form对象
      param.append("file", f.file); //通过append向form对象添加数据
      param.append("type", "DEVICE_PIC"); //添加form表单中其他数据
      upload(param) //上传
        .then(response => {
          if (response.code == "200") {
            this.imgKeys.push({
              imgkey: response.value.key,
              httpUrl: response.value.url
            });
            this.$message.success("上传成功!");
            this.close();
          }
        })
        .catch(({}) => {
          f.onError();
        });
    },
    uploadImgSuccess() {
      this.$message.success("图片上传成功!");
    },
    handleRemove(file, fileList) {
      // 更新缓存文件
      this.$message.success("图片已删除!");
    },
    getMessage() {
      const that = this;
      let data = {
        deviceId: this.deviceId
      };
      get(data).then(res => {
        if (res["code"] == 200) {
          that.formData = res.value;
          for (let i = 0; i < this.formData.imageKeys.length; i++) {
            const element = this.formData.imageKeys[i];
            this.imgKeys.push({ imgkey: element, httpUrl: "" });
            this.getImgFun(element);
          }
          if (
            that.formData.project == null ||
            that.formData.project.projectId == null
          ) {
            // that.formData.projectId = "";
          } else {
            that.formData.projectId = that.formData.project.projectId;
          }
        }
      });
    },
    getProjectList() {
      listSimple().then(res => {
        this.projectOptions = res.value;
      });
    },
    goBack() {
      this.$router.push(this.homePath);
    },
    submit(formName) {
      this.$refs[formName].validate(valid => {
        let imageKeys = this.imgKeys.map(item => {
          return item.imgkey;
        });

        if (valid) {
          const that = this;
          const data = {
            ...that.formData,
            imageKeys
          };
          this.submitLoading = true;
          deploy(data)
            .then(res => {
              this.submitLoading = false;
              if (res["code"] == 200) {
                this.$router.push(this.homePath);
                that.$message.success("部署成功!");
              } else {
                that.$message(res["msg"]);
              }
            })
            .catch(() => {
              this.submitLoading = false;
            });
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    }
  }
};
</script>
<style>
.upload-demo .el-upload-dragger {
  border: 1px solid #ccc;
  width: 300px;
  height: 220px;
}

.upload-demo .el-upload-dragger .el-icon-upload {
  line-height: 100px;
}
</style>
<style scoped>
.el-form {
  width: 90%;
  margin: 20px;
}

.uploadImg {
  width: auto;
  height: 100%;
}

.img-box {
  position: relative;
}

.img-box .close-icon {
  background-color: #fff;
  width: 25px;
  height: 25px;
  line-height: initial;
  border-radius: 100%;
  font-size: 25px;
  color: #999;
  position: absolute;
  right: 5px;
  top: 1px;
}
</style>
